package my2Cents;

import java.io.Serializable;
import java.util.Vector;

import net.phys2d.raw.Body;
import net.phys2d.raw.Joint;
import net.phys2d.raw.World;

public class Undo implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -761083351198698450L;
	
	private final Object obj;
	private final World w;
	private final String txt;
	private final Vector<Undo> groupedUndos = new Vector<Undo>();
	
	public Undo(final Object obj, final World w, final String txt) {
		this.obj = obj;
		this.w = w;
		this.txt = txt;
	}
	
	public void groupUndo(final Undo u) {
		groupedUndos.add(u);
	}
	
	public void performUndo() {
		System.out.println("Performing Undo!");
		if(!this.isValid()) {
			System.err.println("Invalid Undo!");
		}
		if(obj instanceof Body) {
			w.getBodyStateManager().purgeBodyState(Sandbox.BODYSTATES_SANDBOX, (Body) obj);
			w.remove((Body) obj);
		} else if (obj instanceof Joint) {
			w.remove((Joint) obj);
		}
		final int gsize = groupedUndos.size();
		for(int i=0; i<gsize; i++) {
			final Undo u = groupedUndos.get(i);
			u.performUndo();
		}
		
		groupedUndos.removeAllElements();
	}
	
	public String getUndoText() {
		return txt;
	}

	private boolean worldHasObject() {
		if(obj instanceof Body) {
			for(int i=0; i<w.getBodies().size(); i++) {
				if(w.getBodies().get(i) == obj) {
					return true;
				}
			}
		} else if (obj instanceof Joint) {
			for(int i=0; i<w.getJoints().size(); i++) {
				if(w.getJoints().get(i) == obj) {
					return true;
				}
			}
		}
		return false;
	}
	
	public boolean isValid() {
		if(obj != null && worldHasObject()) {return true;}
		return false;
	}
	
	public Object getObject() {
		return obj;
	}
}
